#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    string reverseWords(string s) {
        string str = "";
        int i = 0;
        while (s[i] == ' ') {
            i++;
        }
        int j = s.size() - 1;
        while (s[j] == ' ') {
            j--;
        }
        for (int k = i; k <= j; k++) {
            str += s[k];
        }
        if (i == j)return str;
        int len = j - i + 1;
        string ans = "";
        reverse(str.begin(), str.end());
        string str1;
        for (int i = 0; i < len; i++) {
            str1 += str[i];
        }
        for (int i = 1, j = 0; i < str1.size(); i++) {
            if (str1[i] != ' ' && str1[i - 1] == ' ')j = i;
            if ((str1[i] == ' ' && str1[i - 1] != ' ')) {
                for (int k = i - 1; k >= j; k--) {
                    ans += str1[k];
                }
                if (i != str1.size() - 1)ans += ' ';
            }
            if (i == len - 1) {
                for (int k = i; k >= j; k--) {
                    ans += str1[k];
                }
            }
        }

        return ans;

    }
};